package com.example.shixun.controller;

import com.example.shixun.dao.CourseDao;
import com.example.shixun.interceptor.Teacher;
import com.example.shixun.pojo.*;
import com.example.shixun.service.CourseService;
import com.example.shixun.service.CourseStudentService;
import com.example.shixun.service.LikeCourseService;
import com.example.shixun.service.UserService;
import com.example.shixun.service.impl.UserServiceImpl;
import com.example.shixun.utils.GetIdByToken;
import com.example.shixun.utils.GetNowTime;
import com.example.shixun.utils.PageInfoUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Resource
    CourseService courseService;
    @Resource
    UserService userService;
    @Resource
    GetIdByToken getIdByToken;
    @Resource
    LikeCourseService likeCourseService;
    @Resource
    CourseStudentService courseStudentService;
    //public Result getCourseList(@RequestBody Map<String,String> param){
//        Integer current= Integer.valueOf(param.get("current"));
//        Integer pageSize= Integer.valueOf(param.get("pageSize"));
//        String orderBy=param.get("orderBy");
//        String order=param.get("current");
//        String name=param.get("name");
//        Course course=new Course();

    /**
     *
     * @param pageNum 当前页码
     * @param pageSize 页面条数
     * @param orderBy 排序的词条，比如score
     * @param order 排序的顺序,asc升序，desc降序
     * @param course 根据课程信息查询
     * @return
     */
    @ApiOperation("分页查找课程信息")
    @RequestMapping (value = "/list",method = RequestMethod.GET)
    public Result getCourseList(@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                @RequestParam(value = "orderBy", defaultValue = "name") String orderBy,
                                @RequestParam(value = "order", defaultValue = "asc") String order,
                                Course course){
        PageInfoUtil<Course> pageInfoUtil=new PageInfoUtil<Course>();
        System.out.println(course.toString());
        // 只允许指定的排序字段和排序方式，防止SQL注入
        String[] orderByArr = {"like_number","score","create_time"};
        String orderByStr = "";
        System.out.println("orderBy:"+orderBy+" order:"+order);
        if (orderBy!=null&&orderBy!="" && Arrays.asList(orderByArr).contains(orderBy.toLowerCase())) {
            orderByStr = String.format("%s %s", orderBy.toLowerCase(), "asc".equalsIgnoreCase(order) ? "asc" : "desc");
        } else {
            // 默认排序
            orderByStr = "name asc";
        }
        pageInfoUtil.setPageSize(pageSize);
        pageInfoUtil.setPageNum(pageNum);
        pageInfoUtil.setParams(course);
        pageInfoUtil.setOrderBy(orderByStr);
        PageInfoUtil<Course> pageInfo=courseService.selectCourseAll(pageInfoUtil);
        return Result.success(pageInfo);
    }
    @ApiOperation("根据id查询课程详细信息")
    @RequestMapping(value = "/findById",method = RequestMethod.GET)
    public Result findById(Integer id){
        Course course = courseService.selectCourseById(id);
        if(course!=null){
            return Result.success(course);
        }
        return Result.fail("id有误");
    }

    @ApiOperation("添加课程")
//    @Teacher
    @PostMapping("/save")
    public Result saveCourse(@RequestBody Course course,@RequestHeader String token){
        System.out.println("course:"+course.toString());
        if(course.getCreateTime()==null) course.setCreateTime(GetNowTime.getNowTime());
        if(course.getStartTime()==null) course.setStartTime(GetNowTime.getNowTime());
        if(course.getTeacherId()==null) {
            if (token == null) return Result.fail("请先登录");
            if(userService==null){
                userService=new UserServiceImpl();
            }
            UserDTO user;
            user=userService.getUserTokenInfo(token);
            System.out.println(user);
            course.setTeacherId(user.getId());
        }
        Integer n = courseService.saveCourse(course);
        if(n>0) return Result.success("添加课程成功",n);
        return Result.fail("添加失败");
    }
//    @ApiOperation("点赞")
//    @GetMapping("/like")
//    public Integer like(@RequestParam("id")Integer id){
//        return null;
//    }
    @ApiOperation("根据老师id查课程")
//    @Teacher
    @GetMapping("findByTeacher")
    public Result findByTeacher(@RequestHeader("token")String token,@RequestParam("status") Integer status){
        if (token == null) return Result.fail("请先登录");
        if(userService==null){
            userService=new UserServiceImpl();
        }
        UserDTO user;
        user=userService.getUserTokenInfo(token);
        System.out.println(user);
        int id = (user.getId());
        System.out.println("status="+status);
        Course course=new Course();
        course.setTeacherId(id);
        if(status!=null) course.setStatus(status);
        else System.out.println("status==null");
        List<Course> list=courseService.findByTeacherId(course);
        return Result.success(list);
    }
    @ApiOperation("删除课程")
    @GetMapping("/delete")
    public Result deleteCourse(@RequestParam("id") Integer id){
        return Result.success(courseService.deleteCourseById(id));
    }
    @ApiOperation("学生参加课程")
    @GetMapping("/addStudent")
    public Result addStudent(@RequestParam("courseId") Integer courseId,
                             @RequestHeader("token") String token){
        UserDTO user;
        user=userService.getUserTokenInfo(token);
        Integer studentId=user.getId();
        CourseStudent courseStudent=new CourseStudent();
        courseStudent.setCreateTime(GetNowTime.getNowTime());
        courseStudent.setCourseId(courseId);
        courseStudent.setStudentId(studentId);
        if(courseStudentService.studiedFlag(courseStudent)){
            return Result.fail("参加失败，已参加过此课程");
        }
        courseService.addStudent(courseId);
        return Result.success(courseStudentService.saveCourseStudent(courseStudent));
    }
    @ApiOperation("学生退出课程")
    @GetMapping("/subStudent")
    public Result subStudent(@RequestParam("courseId") Integer courseId,
                             @RequestHeader("token") String token){
        CourseStudent courseStudent=new CourseStudent();
        courseStudent.setCourseId(courseId);
        Integer uid=getIdByToken.getIdByToken(token);
        courseStudent.setStudentId(uid);
        if(!courseStudentService.studiedFlag(courseStudent)){
            return Result.fail("退出失败，未参加过此课程");
        }
        courseService.subStudent(courseId);
        courseStudentService.deletsCourseStudent(courseId,uid);
        return Result.success("已退出课程");
    }
    @ApiOperation("判断是否参加过此课程")
    @GetMapping("/studiedFlag")
    public Result studiedFlag(@RequestParam("courseId") Integer courseId,
                             @RequestHeader("token") String token){
        UserDTO user;
        user=userService.getUserTokenInfo(token);
        Integer studentId=user.getId();
        CourseStudent courseStudent=new CourseStudent();
        courseStudent.setCourseId(courseId);
        courseStudent.setStudentId(studentId);
        if(courseStudentService.studiedFlag(courseStudent)){
            return Result.success("已参加",true);
        }
        return Result.success("未参加",false);
    }
    @ApiOperation("根据id查询参加的课程")
    @GetMapping("/myCourse")
    public Result myCourse(@RequestHeader("token") String token){
        int uid = getIdByToken.getIdByToken(token);
        System.out.println("uid="+uid);
        List<CourseStudent> courseStudentList=courseStudentService.selectCourseStudentByStudentId(uid);
        List<Course> courseList=new ArrayList<>();
        for(CourseStudent list:courseStudentList){
            System.out.println("list:courseId="+list.getCourseId());
            Course course=courseService.selectCourseById(list.getCourseId());
            if(course!=null) courseList.add(course);
        }
        System.out.println("courseList"+courseList);
        return Result.success(courseList);
    }
    @ApiOperation("修改课程")
    @PostMapping("/update")
    public Result updateCourse(@RequestBody Course course){
        course.setUpdateTime(GetNowTime.getNowTime());
        return Result.success(courseService.updateCourse(course));
    }
    @ApiOperation("学生点赞课程")
    @GetMapping("/like")
    public Result like(@RequestParam("courseId") Integer courseId,
                             @RequestHeader("token") String token){
        LikeCourse likeCourse=new LikeCourse();
        likeCourse.setCreateTime(GetNowTime.getNowTime());
        likeCourse.setCourseId(courseId);
        likeCourse.setUserId(getIdByToken.getIdByToken(token));
        if(likeCourseService.likeFlag(likeCourse)>0){
            return Result.fail("点赞失败，已点赞过此课程");
        }
        courseService.addLike(courseId);
        return Result.success(likeCourseService.save(likeCourse));
    }
    @ApiOperation("学生取消点赞课程")
    @GetMapping("/delike")
    public Result delike(@RequestParam("courseId") Integer courseId,
                             @RequestHeader("token") String token){
        LikeCourse likeCourse=new LikeCourse();
        likeCourse.setCourseId(courseId);
        likeCourse.setUserId(getIdByToken.getIdByToken(token));
        if(likeCourseService.likeFlag(likeCourse)<=0){
            return Result.fail("取消失败，未点赞过此课程");
        }
        courseService.subLike(courseId);
        likeCourseService.deleteLike(likeCourse);
        return Result.success("已取消点赞");
    }
    @ApiOperation("判断是否点赞过此课程")
    @GetMapping("/likeFlag")
    public Result likeFlag(@RequestParam("courseId") Integer courseId,
                              @RequestHeader("token") String token){
        LikeCourse likeCourse=new LikeCourse();
        likeCourse.setCourseId(courseId);
        likeCourse.setUserId(getIdByToken.getIdByToken(token));
        if(likeCourseService.likeFlag(likeCourse)>0){
            return Result.success("已点赞",true);
        }
        return Result.success("未点赞",false);
    }
}
